//
//  ClubMyCollectViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/18.
//

import UIKit

class ClubMyCollectViewController: ClubBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("我的收藏").color(.black).font(16.font_semiBold)
        .alignment(.center).end()
    private var cateView = ClubMyCollectCateView()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubNewDiscoverMoreView.self,ClubMyCollectCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
//        tableView.rowHeight = 230.0.Scale
        return tableView
    }()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let emptyView = ClubEmptyView()
    
    private var pageIndex = 1
    //type=1,商品，0=游戏,3=资讯，4=帖子
    private var type = "0"
    private var gameModels = [ClubCollectGamesModel]()
    private var goodsModels = [ClubCollectGoodsModel]()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            backButton
            titleLabel
            cateView
            tableView
            collectionView
            emptyView
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.centerHorizontally()
        titleLabel.CenterY == backButton.CenterY
        cateView.leading(0).top(.navi_height).trailing(0).height(32.0.Scale)
        tableView.leading(0).trailing(0).bottom(.safe_bottom)
        tableView.Top == cateView.Bottom
        collectionView.leading(0).trailing(0).bottom(.safe_bottom)
        collectionView.Top == cateView.Bottom
        emptyView.leading(0).trailing(0).height(200)
        emptyView.Top == cateView.Bottom + 170.0.Scale
        
        emptyView.isHidden = true
        emptyView.titleString = "空空如也哟~"
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        collectionView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        cateView.updateCollectListView = { typeStr in
            self.type = typeStr
            if typeStr == "1" {
                self.tableView.isHidden = true
                self.collectionView.isHidden = false
            }else {
                self.tableView.isHidden = false
                self.collectionView.isHidden = true
            }
            self.loadNewData()
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 12
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: (.screenWidth - 36.0.Scale)/2, height: 240.0.Scale)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12.0.Scale, bottom: 0, right: 12.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubMallGoodsCell.self, forCellWithReuseIdentifier: ClubMallGoodsCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isHidden = true
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        NotificationCenter.default.addObserver(self, selector: #selector(updateCollectList), name: .updateCollectState, object: nil)
    }
    
    @objc private func updateCollectList(){
        self.loadNewData()
    }
    
    private func loadData(){
        
        if type == "1" {
            Task {
                let res = await network.request(.myCollectList(type: type, page: pageIndex),type: ClubCollectGoodsModel.self,isShowError: false)
                collectionView.refresh_end()
                ToastUtil.dismiss()
                if res.isSuccess, let models = res.models {
                    self.goodsModels = models
                    self.emptyView.isHidden = models.count > 0
                    self.collectionView.reloadData()
                }else{
                    self.gameModels.removeAll()
                    self.collectionView.reloadData()
                    emptyView.isHidden = false
                }
            }
        }else{
            Task {
                let res = await network.request(.myCollectList(type: type, page: pageIndex),type: ClubCollectGamesModel.self,isShowError: false)
                tableView.refresh_end()
                ToastUtil.dismiss()
                if res.isSuccess, let models = res.models {
                    self.gameModels = models
                    self.emptyView.isHidden = models.count > 0
                    self.tableView.reloadData()
                }else{
                    self.gameModels.removeAll()
                    self.tableView.reloadData()
                    emptyView.isHidden = false
                }
            }
        }
        
        
    }
    
    @objc private func loadNewData(){
        ToastUtil.show()
        pageIndex = 1
        loadData()
    }
    
    @objc private func loadMoreData(){
        pageIndex += 1
        if type == "1" {
            Task {
                let res = await network.request(.myCollectList(type: type, page: pageIndex),type: ClubCollectGoodsModel.self,isShowError: false)
                collectionView.refresh_end()
                if res.isSuccess, let models = res.models {
                    if models.count > 0 {
                        for mod in models {
                            self.goodsModels.append(mod)
                        }
                    } else {
                        self.collectionView.refresh_end(true)
                    }
                    self.collectionView.reloadData()
                }
            }
        }else{
            Task {
                let res = await network.request(.myCollectList(type: type, page: pageIndex),type: ClubCollectGamesModel.self,isShowError: false)
                tableView.refresh_end()
                if res.isSuccess, let models = res.models {
                    if models.count > 0 {
                        for mod in models {
                            self.gameModels.append(mod)
                        }
                    } else {
                        self.tableView.refresh_end(true)
                    }
                    self.tableView.reloadData()
                }
            }
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubMyCollectViewController: UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return gameModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if type == "0"{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubNewDiscoverMoreView", for: indexPath) as! ClubNewDiscoverMoreView
            cell.collectModel = gameModels[indexPath.row]
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubMyCollectCell", for: indexPath) as! ClubMyCollectCell
            cell.model = gameModels[indexPath.row]
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if type == "0" {
            
            let infoId = gameModels[indexPath.row].gid
            let detailVC = ClubGameDetailViewController()
            detailVC.gameId = infoId
            self.navigationController?.pushViewController(detailVC, animated: true)
        }else if type == "3" {
            
            let model = gameModels[indexPath.row]
            let webView = ClubWebViewController()
            var urlStr = model.webview_url
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                urlStr = urlStr + "&uid=\(uid)"
            }
            urlStr = urlStr + "&model=ios"
            webView.urlString = urlStr
            webView.titleName = "资讯详情"
            webView.ishiddenNav = true
            self.navigationController?.pushViewController(webView, animated: true)
        }else{
            
            let model = gameModels[indexPath.row]
            if model.is_bbs == 1 {
                if model.news_uid == "0" {
                    let detailVC = ClubForumDetailViewController()
                    detailVC.newId = model.news_id
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }else{
                    let detailVC = ClubSquareForumDetailViewController()
                    detailVC.postID = model.news_id
//                    detailVC.pid = self.communityId
//                    detailVC.communityModel = self.model
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }
            }else{
                if model.news_uid == "0" {
                    let detailVC = ClubForumDetailViewController()
                    detailVC.newId = model.news_id
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }else{
                    let detailVC = ClubGameForumDetailViewController()
                    detailVC.postID = model.news_id
//                    detailVC.pid = self.communityId
//                    detailVC.gameModel = self.gameModel
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }
            }
        }        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if type == "0"{
            return 230.0.Scale
        }else{
            return 78.0.Scale
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return goodsModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubMallGoodsCell.description(), for: indexPath) as? ClubMallGoodsCell else { return UICollectionViewCell() }
        cell.collectModel = goodsModels[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let md = goodsModels[indexPath.row]
        let detailVC = ClubIntegralDetailViewController()
        detailVC.goodsId = md.goods_id
        detailVC.collectId = md.id
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
}
